package com.yycx.module.weixin.provider.client;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.utils.SpringContextHolder;
import com.yycx.module.weixin.client.dto.MessageRequest;
import com.yycx.module.weixin.client.entity.SysTemplateMessageLog;
import com.yycx.module.weixin.client.entity.SysWechat;
import com.yycx.module.weixin.client.entity.SysWechatTemplate;
import com.yycx.module.weixin.provider.handler.MessageSendHandler;
import com.yycx.module.weixin.provider.handler.WxMpTemplateDataHandler;
import com.yycx.module.weixin.provider.service.SysTemplateMsgLogService;
import com.yycx.module.weixin.provider.service.SysWechatService;
import com.yycx.module.weixin.provider.service.SysWechatTemplateService;
import com.yycx.module.weixin.provider.service.impl.WeiXinOpenService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 微信模板消息发送客户端
 *
 * @author zyf
 */
@Component
@AllArgsConstructor
public class WxTemplateMessageClient {

    private final WxMpService wxMpService;

    private final WeiXinOpenService weiXinOpenService;

    private final SysWechatTemplateService sysWechatTemplateService;

    private final SysWechatService sysWechatService;

    private final SysTemplateMsgLogService templateMsgLogService;


    /**
     * 公共发送微信通知
     *
     * @param messageRequest
     * @param messageSendHandler
     */
    public ResultBody sendMessage(MessageRequest messageRequest, MessageSendHandler messageSendHandler) {
        Integer useWxTemplateType = messageRequest.getUseWxTemplateType();
        if (FlymeUtils.isEmpty(useWxTemplateType)) {
            return ResultBody.failed("微信服务类型不能为空");
        }
        String openId = messageRequest.getOpenId();
        if (FlymeUtils.isEmpty(openId)) {
            return ResultBody.failed("openId不能为空");
        }
        String appId = messageRequest.getAppId();
        if (FlymeUtils.isEmpty(appId)) {
            return ResultBody.failed("appId不能为空");
        }
        String templateCode = messageRequest.getTemplateCode();
        if (FlymeUtils.isEmpty(templateCode)) {
            return ResultBody.failed("templateCode不能为空");
        }
        SysWechat wechat = sysWechatService.getByAppId(appId);
        Long weChatId = wechat.getWeChatId();
        SysWechatTemplate wechatTemplate = sysWechatTemplateService.findByWeChatAndCode(weChatId, templateCode);
        if (FlymeUtils.isEmpty(wechatTemplate)) {
            return ResultBody.failed("模板消息配置不存在");
        }
        //是否启用
        Integer isEnable = FlymeUtils.getInteger(wechatTemplate.getIsEnable(), 0);
        if (isEnable == 0) {
            return ResultBody.failed("该微信消息模板未启用");
        }
        String templateId = wechatTemplate.getTemplateId();

        //跳转地址
        String url = messageRequest.getUrl();

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .templateId(templateId)
                .toUser(openId)
                .url(url)
                .build();

        //处理模板参数
        if (FlymeUtils.isNotEmpty(messageSendHandler)) {
            messageSendHandler.initMessageRequest(messageRequest);
        }
        //消息模板参数
        for (Map.Entry<String, String> entry : messageRequest.getAttr().entrySet()) {
            String value = entry.getValue();
            WxMpTemplateData wxMpTemplateData = new WxMpTemplateData(entry.getKey(), value);
            templateMessage.addData(wxMpTemplateData);
        }
        //处理消息模块参数
        WxMpTemplateDataHandler wxMpTemplateDataHandler = SpringContextHolder.getHandler(messageRequest.getHandlerName(), WxMpTemplateDataHandler.class);
        if (FlymeUtils.isNotEmpty(wxMpTemplateDataHandler)) {
            List<WxMpTemplateData> templateMessageData = templateMessage.getData();
            wxMpTemplateDataHandler.init(templateMessageData);
            templateMessage.setData(templateMessageData);
        }
        WxMpTemplateMsgService templateMsgService = null;
        if (useWxTemplateType == 1) {
            wxMpService.switchover(appId);
            templateMsgService = wxMpService.getTemplateMsgService();
        } else {
            String componentAppId = wechat.getComponentAppId();
            if (FlymeUtils.isEmpty(componentAppId)) {
                return ResultBody.failed("未配置微信开放平台配置");
            }
            weiXinOpenService.switchover(componentAppId);
            templateMsgService = weiXinOpenService.getWxOpenComponentService().getWxMpServiceByAppid(appId).getTemplateMsgService();
        }
        //构建消息日志
        SysTemplateMessageLog msgLog = templateMsgLogService.initTemplateMsgLog(templateMessage, weChatId, 0);
        msgLog.setSourceType(messageRequest.getSourceType());
        try {
            templateMsgService.sendTemplateMsg(templateMessage);
            msgLog.setSendState(CommonConstants.INT_1);
        } catch (Exception e) {
            msgLog.setSendState(CommonConstants.INT_0);
            msgLog.setErrorInfo(e.getMessage());
        }
        templateMsgLogService.save(msgLog);
        EntityMap entityMap = new EntityMap();
        entityMap.put("sendState", msgLog.getSendState());
        return ResultBody.ok(entityMap);
    }


    /**
     * 公共发送微信通知
     *
     * @param messageRequest
     */
    public ResultBody sendMessage(MessageRequest messageRequest) {
        return sendMessage(messageRequest, null);
    }

}
